package com.gamesite.gamesite.core.socket;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gamesite.gamesite.core.pojo.User;
import com.gamesite.gamesite.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

@ServerEndpoint("/ws/chatRoom")
@Component
public class ChatRoomEndpoint {
    @Autowired
    private UserService userService;
    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());
    private static final Map<Session, User> userMap = new HashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("Connected: " + session.getId());
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Message from " + session.getId() + ": " + message);
        try {
            // 解析消息
            JSONObject jsonMessage = JSONObject.parseObject(message);
            String type = jsonMessage.getString("type");
            switch (type) {
                case "setId":
                    bindSessionUserInfo(session, jsonMessage);
                    break;
                case "sendMessage":
                    handSendMessage(session, jsonMessage);
                    break;
                default:
                    System.out.println("未知消息类型: " + type);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        userMap.remove(session); // 移除用户信息
        System.out.println("Disconnected: " + session.getId());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }
    // 绑定用户信息到session
    private void bindSessionUserInfo(Session session, JSONObject jsonMessage) {
        // 从数据库中获取用户信息
        Integer userId = Integer.parseInt(jsonMessage.getString("userId"));
        User user = userService.getById(userId);
        if (user != null) { // 确保用户对象不为null
            userMap.put(session, user);
        } else {
            System.err.println("User not found with ID: " + userId);
        }
    }
    // 发送消息
    private void handSendMessage(Session session, JSONObject jsonMessage) {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> messageReturn = new HashMap<>();

        // 获取消息内容
        String content = jsonMessage.getString("content");
        if (content == null || content.trim().isEmpty()) {
            return; // 如果消息内容为空或仅包含空白字符，则不执行后续操作
        }

        User sender = null;
        for (Map.Entry<Session, User> entry : userMap.entrySet()) {
            if (entry.getKey().equals(session)) {
                sender = entry.getValue();
                break;
            }
        }

        if (sender == null) {
            return; // 如果找不到对应的用户，则不执行后续操作
        }

        // 构建要返回的消息
        messageReturn.put("type", "broadcastMessage");
        messageReturn.put("senderName", sender.getUsername()); // 发送者用户名
        messageReturn.put("content", content); // 消息内容
        messageReturn.put("sendTime", new Date()); // 当前时间作为发送时间

        String jsonData;
        try {
            jsonData = objectMapper.writeValueAsString(messageReturn);
        } catch (Exception e) {
            return; // 如果序列化失败，则不执行后续操作
        }

        synchronized (sessions) {
            for (Session s : sessions) {
                if (s.isOpen()) { // 确保会话是打开状态
                    try {
                        s.getBasicRemote().sendText(jsonData);
                    } catch (IOException e) {
                        // 忽略发送失败的异常，继续向其他会话发送
                    }
                }
            }
        }
    }
}
